package org.example.ui;

import org.example.dao.EmployeeDao;
import org.example.dao.impl.EmployeeDaoImpl;
import org.example.entity.Employee;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class EmployeeManagementPanel1 extends JPanel {
    public JTable table;
    private JLabel label;
    private EmployeeDao employeeDao = new EmployeeDaoImpl();
    private DefaultTableModel tableModel;

    public EmployeeManagementPanel1() {
        setLayout(new BorderLayout());

        // 北部面板，放置提醒输入新员工信息的文本框
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
        label = new JLabel("输入要添加的员工信息：");
        label.setFont(new Font("行书", Font.BOLD, 25));
        panel1.add(label);
        add(panel1, BorderLayout.NORTH);

        // 中间面板，放置表格
        JPanel panel2 = new JPanel();
        panel2.setLayout(new BorderLayout());

        String[] columnNames = {"姓名", "职位", "雇佣日期", "薪资", "佣金", "部门ID"};
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);
        table.setShowHorizontalLines(true);
        table.setShowVerticalLines(true);
        table.setGridColor(new Color(220, 220, 220));
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        panel2.add(scrollPane, BorderLayout.CENTER);

        // 添加行按钮
        JButton addRowButton = new JButton("添加行");
        addRowButton.setPreferredSize(new Dimension(200, 50));
        addRowButton.addActionListener(e -> tableModel.addRow(new Object[]{"", "", "", "", "", "", ""}));
        panel2.add(addRowButton, BorderLayout.SOUTH);
        add(panel2, BorderLayout.CENTER);

        // 南部面板，放置提交按钮
        JPanel panel3 = new JPanel();
        JButton admit = new JButton("提交");
        admit.setPreferredSize(new Dimension(200, 50));
        admit.addActionListener(new AdmitButtonListener());
        panel3.add(admit);
        add(panel3, BorderLayout.SOUTH);

        // 加载数据库中的员工信息
        loadEmployees();
    }

    private void loadEmployees() {
        tableModel.setRowCount(0);
        List<Employee> employees = employeeDao.getAllEmployees();
        for (Employee employee : employees) {
            tableModel.addRow(new Object[]{
                    employee.getEmpName(),
                    employee.getJob(),
                    employee.getHireDate(),
                    employee.getSal(),
                    employee.getComm(),
                    employee.getDept_id()
            });
        }
    }

    private class AdmitButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int rowCount = tableModel.getRowCount();
            boolean hasError = false;

            for (int i = 0; i < rowCount; i++) {
                // 检查职位是否填写（职位是必填项）
                if (tableModel.getValueAt(i, 1) != null && !tableModel.getValueAt(i, 1).toString().isEmpty()) {
                    Employee employee = new Employee();

                    try {
                        // 修正索引位置
                        employee.setEmpName(tableModel.getValueAt(i, 0).toString());  // 姓名：索引0
                        employee.setJob(tableModel.getValueAt(i, 1).toString());     // 职位：索引1

                        // 处理日期
                        Object dateObj = tableModel.getValueAt(i, 2);
                        if (dateObj == null || dateObj.toString().isEmpty()) {
                            JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                    "第 " + (i + 1) + " 行的雇佣日期不能为空！");
                            hasError = true;
                            continue;
                        }

                        String dateStr = dateObj.toString();
                        if (!dateStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
                            JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                    "第 " + (i + 1) + " 行的日期格式错误，请使用yyyy-MM-dd格式！");
                            hasError = true;
                            continue;
                        }

                        java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
                        employee.setHireDate(new Date(utilDate.getTime()));

                        // 处理薪资
                        Object salObj = tableModel.getValueAt(i, 3);
                        if (salObj == null || salObj.toString().isEmpty()) {
                            JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                    "第 " + (i + 1) + " 行的薪资不能为空！");
                            hasError = true;
                            continue;
                        }
                        employee.setSal(Double.parseDouble(salObj.toString()));

                        // 处理佣金
                        Object commObj = tableModel.getValueAt(i, 4);
                        if (commObj == null || commObj.toString().isEmpty()) {
                            employee.setComm(0.0); // 佣金可以为空，默认为0
                        } else {
                            employee.setComm(Double.parseDouble(commObj.toString()));
                        }

                        // 处理部门ID
                        Object deptIdObj = tableModel.getValueAt(i, 5);
                        if (deptIdObj == null || deptIdObj.toString().isEmpty()) {
                            JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                    "第 " + (i + 1) + " 行的部门ID不能为空！");
                            hasError = true;
                            continue;
                        }
                        employee.setDept_id(Integer.parseInt(deptIdObj.toString()));

                        // 添加员工
                        employeeDao.addEmp(employee);

                    } catch (NullPointerException ex) {
                        JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                "第 " + (i + 1) + " 行存在空值，请检查！");
                        hasError = true;
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                "第 " + (i + 1) + " 行的薪资、佣金或部门ID格式错误！");
                        hasError = true;
                    } catch (ParseException ex) {
                        JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                "第 " + (i + 1) + " 行的日期格式错误，请使用yyyy-MM-dd格式！");
                        hasError = true;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(EmployeeManagementPanel1.this,
                                "添加第 " + (i + 1) + " 行员工时出错：" + ex.getMessage());
                        hasError = true;
                    }
                }
            }

            if (!hasError) {
                JOptionPane.showMessageDialog(EmployeeManagementPanel1.this, "数据提交成功！");
                loadEmployees(); // 重新加载数据
            }
        }
    }
}